package com.jike.mahjong.service.Imp;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jike.mahjong.common.Constants;
import com.jike.mahjong.common.util.HttpUtil;
import com.jike.mahjong.common.util.MD5Util;
import com.jike.mahjong.common.util.TransSerialNumTool;
import com.jike.mahjong.dao.ClubDao;
import com.jike.mahjong.dao.PersonDao;
import com.jike.mahjong.model.ApplicationForm;
import com.jike.mahjong.model.Club;
import com.jike.mahjong.model.ClubPlayerMapping;
import com.jike.mahjong.model.Manager;
import com.jike.mahjong.model.NoticeMsg;
import com.jike.mahjong.model.Player;
import com.jike.mahjong.model.RequestMethod;
import com.jike.mahjong.model.RequestModel;
import com.jike.mahjong.service.ClubService;

@Service("clubService")
@Transactional(rollbackFor={Exception.class,RuntimeException.class})
public class ClubServiceImpl implements ClubService {

	@Autowired
	private ClubDao dao;
	
    @Autowired
    private PersonDao personDao;
	
	@Override
	public Integer insertClub(Club club) {
		if(dao.addClub(club)>0){
			HashMap<String,Object> map=new HashMap<>();
			map.put("managerId", club.getClubManagerId());
			Manager agent=dao.selectManagerInfo(map);
			if(agent!=null){
				ClubPlayerMapping mapping=new ClubPlayerMapping();
				mapping.setClubId(club.getClubId());
				mapping.setAdvanceDiamond(Constants.CLUB_DEFAULT_DIAMOND);
				mapping.setPlayerId(Integer.parseInt(agent.getPlayerId()));
				return dao.addClubPlayerMapping(mapping);
			}
		}
		return 0;
	}

	@Override
	public Club selectClubById(String clubId) {
		return dao.selectClubById(clubId);
	}

	@Override
	public Integer updateClubInfo(Club club) {
		return dao.updateClubInfo(club);
	}

	@Override
	public Integer insertClubMapping(ClubPlayerMapping mapping,Club club) {
		ClubPlayerMapping tempMapping=dao.selectMapping(mapping);
		if(tempMapping!=null){
			
			//已绑定 需要先删除
			if(dao.deleteClubMapping(mapping.getPlayerId().toString())<1){
				return 0;
			};
		}
		Map<String, Object> param=new HashMap<>();
		param.put("playerId", mapping.getPlayerId());
		if(dao.selectClubSize(param)<1 && Constants.envFlag){//第一次绑定俱乐部
			List<String> args=new ArrayList<String>();
			RequestModel requestModel=new RequestModel();
	        requestModel.setCmd(RequestMethod.addDiamond);
	        args.add(mapping.getPlayerId().toString());
	        args.add(Constants.CLUB_DEFAULT_DIAMOND.toString());
	        requestModel.setArgs(args);

	        int resultUpdate = 0;
	        // resultUpdate = playerDao.addCoin(para);
	        Gson gson=new Gson();
	        String paraStr= gson.toJson(requestModel);
	        String result= HttpUtil.PostWithJson(Constants.BACK_URL,paraStr);
	        JsonParser jsonParser=new JsonParser();
	        JsonObject jsonObject=jsonParser.parse(result).getAsJsonObject();
	        resultUpdate=Integer.parseInt(String.valueOf(jsonObject.get("res")));
	        if(resultUpdate>0){
	        	System.out.println("加钻成功"+resultUpdate);
	        }else{
	        	System.err.println("加钻失败，金额："+Constants.CLUB_DEFAULT_DIAMOND);
	        	new Exception("加钻失败，金额："+Constants.CLUB_DEFAULT_DIAMOND);
	        	return 0;
	        }
		}
		param.remove("playerId");
		param.put("clubId", club.getClubId());
		if(dao.addClubPlayerMapping(mapping)>0){
			return dao.updateClubSize(param);
		}
		return 0;
	}

	@Override
	public Club selectClubByPlayerId(String playerId) {
		List<Club> clubs=dao.selectClubByPlayerId(playerId);
		if(clubs!=null){
			return clubs.get(0);
		}
		return null;
	}

	@Override
	public ClubPlayerMapping selectByPlayerId(String playerId) {
		ClubPlayerMapping mapping=new ClubPlayerMapping();
		mapping.setPlayerId(Integer.valueOf(playerId));
		return dao.selectMapping(mapping);
	}

	@Override
	public Player selectPlayerInfo(String playerId) {
		return dao.selectPlayerInfo(playerId);
	}

	@Override
	public Manager checkPlayerIsManager(String playerId) {
		// TODO Auto-generated method stub
		return dao.checkPlayerIsManager(playerId);
	}

	@Override
	public Manager selectManager(Map map) {
		// TODO Auto-generated method stub
		return dao.selectManagerInfo(map);
	}

	@Override
	public Integer selectClubId(String clubId) {
		return dao.selectClubId(clubId);
	}

	@Override
	public Integer sendNoticeMsg(NoticeMsg msg) {
		msg.setNoticeId(TransSerialNumTool.createSerialNum());
		if(dao.addNoticeMsg(msg)>0){
	        List<String> args = new ArrayList<String>();
	        RequestModel requestModel = new RequestModel();
	        requestModel.setCmd(RequestMethod.sendNotice);
	        args.add(msg.getContent());
	        args.add(msg.getNoticeType()+"");
	        requestModel.setArgs(args);
	        System.out.println(msg.getContent() + new SimpleDateFormat("YYYY-MM-DD hh:mm:ss").format(new Date()));
	        Gson gson = new Gson();
	        String paraStr = gson.toJson(requestModel);
	        if(Constants.envFlag){
	        	String result = HttpUtil.PostWithJson(Constants.BACK_URL, paraStr);
	        	System.err.println(result);
	        }
	        System.out.println(paraStr);
			return 1;
		}
		return 0;
	}

	@Override
	public Integer clearPlayer(String palyerId) {
		List<String> args = new ArrayList<String>();
        RequestModel requestModel = new RequestModel();
        requestModel.setCmd(RequestMethod.clearPlayer);
        args.add(palyerId);
        requestModel.setArgs(args);
        System.out.println("清除玩家数据:ID["+palyerId+"]" + new SimpleDateFormat("YYYY-MM-DD hh:mm:ss").format(new Date()));
        Gson gson = new Gson();
        String paraStr = gson.toJson(requestModel);
        if(Constants.envFlag){
        	String result = HttpUtil.PostWithJson(Constants.BACK_URL, paraStr);
        	System.err.println(result);
        }
        System.out.println(paraStr);
		return 1;
	}

	@Override
	public Integer deleteClubMapping(String playerId) {
		if(dao.selectPlayerIsManager(playerId)>0){
			return 0;
		}
		return dao.deleteClubMapping(playerId);
	}

	@Override
	public Integer addAgent(Manager agent, Map param) {
		agent.setPassword(MD5Util.GetMD5Code(Constants.DEFAULT_PWD));
		if(personDao.addManager(agent)>0){
			String clubName=(String) param.get("clubName");
			Club club=new Club();
	    	if(StringUtils.isBlank(clubName) || StringUtils.isBlank(agent.getId())){
	    		new Exception("添加俱乐部时出错!俱乐部名称或者管理员ID为空");
	    		return 0;
	    	}
	    	Random random = new Random();
	        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
	        while(selectClubId(String.valueOf(rannum))>0){
	        	rannum=(int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
	        }
	        club.setClubId(rannum);
	    	club.setClubManagerId(Integer.valueOf(agent.getId()));
			club.setClubName(clubName);
			club.setClubSize(1);
			club.setClubNotice("公告");
			return insertClub(club);
		}
		return 0;
	}

	@Override
	public List<ApplicationForm> getApplicationorm(Map param) throws UnsupportedEncodingException {
		
		if(param.get("formId")!=null && param.get("watchFlag")!=null){
			int result=dao.updateAppFormState(param);
			System.err.println("更新表单状态:ID--"+param.get("formId").toString()+"----是否更新成功?"+(result>0?"是":"否"));
		}
		if(param.get("formId")!=null && param.get("desc")!=null){
			param.put("desc", new String(param.get("desc").toString().getBytes("ISO-8859-1"),"utf-8"));
			int result=dao.updateAppFormDesc(param);
			System.err.println("更新表单备注:ID--"+param.get("formId").toString()+"---备注内容:"+param.get("desc").toString()+"----是否更新成功?"+(result>0?"是":"否"));
		}
		// TODO Auto-generated method stub
		return dao.getApplicationorm(param);
	}

	@Override
	public Integer upOrDownLevel(String managerId) {
		return dao.upOrDownLevel(managerId);
	}

	@Override
	public Integer updateAdminDesc(Map map) {
		return dao.updateAdminDesc(map);
	}

	@Override
	public Map getNoticeMsg(Map map) {
		map.put("rows", dao.selectNoticeMsg(map));
		if(map.get("last")!=null){
			map.put("total", dao.countNoticeMsg(map));
		}
		return map;
	}
}
